package com.nb.nbbase2.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    //BhCJLSgrdFgvjNUD
    // 密钥，应该足够复杂且保密
    private static final String SECRET_KEY = "BhCJLSgrdFgvjNUD";

    // JWT的有效期（分钟）
    private static final long EXPIRATION_TIME = 864_000_000; // 10天

    // 生成JWT
    public static String generateToken(String userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId); // 将用户ID添加到JWT的负载中

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 解析JWT
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    public static String getUserId(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
        return (String) claims.get("userId");
    }

    // 验证JWT是否有效
    public static boolean validateToken(String token, String userId) {
        final String extractedUserId = parseToken(token).get("userId").toString();
        return (extractedUserId.equals(userId) && !isTokenExpired(token));
    }

    // 检查JWT是否过期
    public static boolean isTokenExpired(String token) {
        return parseToken(token).getExpiration().before(new Date());
    }
}